package com.djf.djfword.controller;

import com.djf.djfword.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;

/**
 * Word文档操作控制器
 * 
 * @author djf
 */
@Controller
@RequestMapping("/word")
public class WordController {

    @Autowired
    private WordService wordService;

    /**
     * 首页
     */
    @GetMapping("/")
    public String index() {
        return "index";
    }

    /**
     * 生成简单Word文档
     */
    @GetMapping("/simple")
    public void generateSimpleWord(HttpServletResponse response,
                                   @RequestParam(defaultValue = "SpringBoot Word示例") String title,
                                   @RequestParam(defaultValue = "这是一个使用SpringBoot和Apache POI生成的Word文档示例。\n\n" +
                                           "主要功能包括：\n" +
                                           "1. 创建简单的Word文档\n" +
                                           "2. 添加标题和内容\n" +
                                           "3. 设置字体样式\n" +
                                           "4. 支持中文显示\n\n" +
                                           "这个示例展示了如何在SpringBoot项目中集成Apache POI来操作Word文档。") String content) throws IOException {
        wordService.createSimpleWord(response, title, content);
    }

    /**
     * 生成包含表格的Word文档
     */
    @GetMapping("/table")
    public void generateTableWord(HttpServletResponse response) throws IOException {
        // 模拟表格数据
        List<Map<String, String>> tableData = new ArrayList<>();
        
        Map<String, String> row1 = new HashMap<>();
        row1.put("name", "张三");
        row1.put("age", "25");
        row1.put("position", "Java开发工程师");
        tableData.add(row1);
        
        Map<String, String> row2 = new HashMap<>();
        row2.put("name", "李四");
        row2.put("age", "28");
        row2.put("position", "前端开发工程师");
        tableData.add(row2);
        
        Map<String, String> row3 = new HashMap<>();
        row3.put("name", "王五");
        row3.put("age", "30");
        row3.put("position", "项目经理");
        tableData.add(row3);
        
        Map<String, String> row4 = new HashMap<>();
        row4.put("name", "赵六");
        row4.put("age", "26");
        row4.put("position", "测试工程师");
        tableData.add(row4);
        
        wordService.createWordWithTable(response, tableData);
    }

    /**
     * 生成模板Word文档
     */
    @GetMapping("/template")
    public void generateTemplateWord(HttpServletResponse response,
                                     @RequestParam(defaultValue = "SpringBoot与Word集成报告") String title,
                                     @RequestParam(defaultValue = "SpringBoot是一个优秀的Java开发框架，它简化了Spring应用的创建和部署。" +
                                             "通过集成Apache POI库，我们可以轻松地在SpringBoot应用中生成和操作Word文档。\n\n" +
                                             "这种集成方案在企业级应用中非常有用，特别是在需要生成报告、合同、证书等文档的场景中。" +
                                             "Apache POI提供了丰富的API来操作Microsoft Office文档，包括Word、Excel和PowerPoint。") String content,
                                     @RequestParam(defaultValue = "系统管理员") String signature) throws IOException {
        Map<String, String> data = new HashMap<>();
        data.put("title", title);
        data.put("content", content);
        data.put("date", LocalDate.now().toString());
        data.put("signature", signature);
        
        wordService.createTemplateWord(response, data);
    }

    /**
     * 上传并读取Word文档
     */
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadAndReadWord(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要上传的文件");
                return result;
            }
            
            // 检查文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".docx") && !fileName.endsWith(".doc"))) {
                result.put("success", false);
                result.put("message", "请上传Word文档文件（.doc或.docx格式）");
                return result;
            }
            
            // 读取文档内容
            String content = wordService.readWordContent(file.getInputStream());
            
            result.put("success", true);
            result.put("message", "文档读取成功");
            result.put("fileName", fileName);
            result.put("content", content);
            result.put("fileSize", file.getSize());
            
        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文档读取失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 自定义表格数据生成Word
     */
    @PostMapping("/custom-table")
    public void generateCustomTableWord(HttpServletResponse response,
                                        @RequestBody List<Map<String, String>> tableData) throws IOException {
        wordService.createWordWithTable(response, tableData);
    }

    /**
     * 批量生成Word文档（演示）
     */
    @GetMapping("/batch")
    @ResponseBody
    public Map<String, Object> batchGenerate() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里可以实现批量生成逻辑
            // 例如：根据数据库数据批量生成报告
            
            result.put("success", true);
            result.put("message", "批量生成功能演示 - 实际项目中可以根据需求实现具体逻辑");
            result.put("generatedCount", 0);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量生成失败：" + e.getMessage());
        }
        
        return result;
    }
}